package _2022.hot100._337_打家劫舍III;

import java.util.HashMap;
import java.util.Map;

/**
 * @author： YHSimon
 * @date： 2022-05-30 10:01
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    private Map<TreeNode,Integer> f=new HashMap<>();
    private Map<TreeNode,Integer> g=new HashMap<>();
    public int rob(TreeNode root){
        dfs(root);
        return Math.max(f.getOrDefault(root, 0), g.getOrDefault(root, 0));
    }

    public void dfs(TreeNode node){
        if(node==null){
            return;
        }
        dfs(node.left);
        dfs(node.right);
        f.put(node,node.val+g.getOrDefault(node.left, 0)+g.getOrDefault(node.right, 0));
        g.put(node, Math.max(f.getOrDefault(node.left, 0),g.getOrDefault(node.left, 0))+Math.max(f.getOrDefault(node.right, 0),g.getOrDefault(node.right, 0)));
    }
}
